
new Vue({
	el:'#successPage',
	data(){

		return {
			openId:'',
			courseId: '',
			contactName: '',
			contactPhone: '',
			contactLocation:'',
			groupOrderId:'',
			referral: '', // 推荐码
			loading:false,

			

			//课程
			courseItems: [
				{ 'name': 'Wonders--启蒙班', id: 10001 ,people:'（2～4人）' ,detail:'适合英语零基础的孩子'},
				{ 'name': 'Wonders--基础班', id: 10002 ,people:'（2～4人）' ,detail:'适合已有一年左右英语学习基础的孩子'},
				{ 'name': 'Wonders--进阶班', id: 10003 ,people:'（2～4人）' ,detail:'适合已有两年及以上英语学习基础的孩子'},
			],
			
			locationList:[],
			changeLocation: '',
			showSearch:false,
			isSubmitBtnClicked: false, // 去邀请朋友试听按钮是否已点击
			allowOtherJoin: false, // 是否允许附近其他小朋友参加我发起的拼班
		}
	},
	methods:{
		getUrlData(dataName){
			function getUrlVars(){ 
        var vars = {}, hash; 
        var href = window.location.href.split('#')[0];
        var hashes = href.slice(href.indexOf('?')+1).split('&'); 
        for(var i = 0; i < hashes.length; i++) { 
            hash = hashes[i].split('=');
            vars[hash[0]] = hash[1]?hash[1]:'';
        } 
        return vars; 
			} 
			var params = getUrlVars(); 
			
			for(var key in params){
					if(key == dataName){ 
							return params[key];
					}
			};
			return '';
		},

		
		getCourseName(courseId){
			var courseItems = this.courseItems;
			for (var i = 0; i < courseItems.length;i++){
				if (courseItems[i].id == courseId){
					return courseItems[i].name;
				}
			}
		},
		getCourseId(name){
			if(name=='英语零基础'){
				return 10001;
			}else if(name=='英语1年学习基础'){
				return 10002;
			}else{
				return 10003;
			}
		},
		//创建团
		createGroup(){
			var self = this;
	
			if (!self.courseId) {
				guigu.showModal({
					content: '请选择体验课程',
					showCancel: false
				});
			}else if (self.contactName == ''){
				guigu.showModal({
					content: '请填写联系人',
					showCancel: false
				});
			}else if (!/^1\d{10}$/.test(self.contactPhone)){
				guigu.showModal({
					content: '请填写正确的联系电话',
					showCancel: false
				});
			}else if(!self.contactLocation){
				guigu.showModal({
					content: '请填写城市和小区名称',
					showCancel: false
				});
			}else{
				// 极端情况处理，如果用户没有同意授权地址，仍选我的位置，则弹出提示
				if(self.contactLocation === self.changeLocation.cityname) {
					guigu.showModal({
						content: '由于您没有授权位置服务，我们无法获取您的位置信息，这将严重影响其他人加入您的拼班，建议您选择一个具体的地点或授权后再使用“我的位置',
						showCancel: true,
						okText:'重新选择',
						cancelText:'我要继续',
						cancelGray:true,
						okFn:function(){
							self.contactLocation = '';
							self.locationFocus();
						},
						cancelFn: function () {
							self.createGroupIng();
						}
					});
					return;
				}
				this.createGroupIng();
			}
		},
		createGroupIng(){
			var self = this;
			// 阻止邀请试听多次点击可能误提交
			if (this.isSubmitBtnClicked) {
				return;
			}
			this.isSubmitBtnClicked = true; // 将按钮状态改为已点击
			//检测并开启loading
			guigu.showLoading({
				title: '数据加载中',
				mask: true
			});
			var putData = {
				"courseId": this.courseId,
				"visibility": this.allowOtherJoin
			};

			// 判断是否有推荐码，有则保存
			if (this.referral) {
				putData.referral = this.referral;
			}

			$.ajax({
				url: 'https://api.svenglish.cn/api/order/group',
				type: 'PUT',
				contentType: 'application/json',
				data: JSON.stringify(putData),
				success:function(data){
					//关闭loading
					guigu.hideLoading();

					if (data.code==1) {
						self.groupOrderId = data.data.groupOrderId;
						self.addGroup();

						//创建团的时候,微信外部浏览器记录本地创建的团单。用于其他页面判断是否发起人
						if(!self.isWeiXin()){
							var createGroupOrderIds = localStorage.getItem('createGroupOrderIds');
							if(createGroupOrderIds){
								createGroupOrderIds += ','+self.groupOrderId;
							}else{
								createGroupOrderIds = self.groupOrderId;
							};
							localStorage.setItem('createGroupOrderId',createGroupOrderIds);
						}

					}else{
						guigu.showModal({
							content: data.msg,
							showCancel: false
						});
						this.isSubmitBtnClicked = false; // 将按钮状态改为可点击
					}
				},
				fail(res) {
					//关闭loading
					guigu.hideLoading();
					guigu.showModal({
						content: JSON.stringify(res),
						showCancel: false
					});
					this.isSubmitBtnClicked = false; // 将按钮状态改为可点击
				}
			});
		},
		//加入团
		addGroup(){
			var self = this;
			
			var putData = {
				"groupOrderId": this.groupOrderId,
				"openId": this.openId,
				"originator": true,  //是否发起人
				"courseId": this.courseId,  //课程ID
				"contactName": this.contactName,
				"contactPhone": this.contactPhone,
				"contactLocation": this.contactLocation,
				"amount": 0,
				"locationCity": this.changeLocation.cityname,
				// "locationDistrict": this.changeLocation.district,
				"locationLatitude": this.changeLocation.latlng.lat,
				"locationLongitude": this.changeLocation.latlng.lng,
				// "locationProvince": this.changeLocation.province,
				"locationAddress": this.changeLocation.poiaddress
			};
	
			//检测并开启loading
			guigu.showLoading({
				title: '数据加载中',
				mask: true
			})
				
			$.ajax({
				url: 'https://api.svenglish.cn/api/order/course',
				type: 'PUT',
				contentType: 'application/json',
				data: JSON.stringify(putData),
				success:function(data){
					//成功
					if (data.code==1) {
						
						//拼团成功，调取支付
					//	self.pretend(data.data.orderId,putData.groupOrderId);
					location.href = 'group.html?groupOrderId=' + putData.groupOrderId;	
					}else{
						//关闭loading
						guigu.hideLoading();
						guigu.showModal({
							content: data.msg,
							showCancel: false
						});
					}
				},
				fail(res) {
					//关闭loading
					guigu.hideLoading();
					guigu.showModal({
						content: '请求失败，请重试！',
						showCancel: false
					});
				}
			});
		},
		pretend(orderId,groupOrderId){
			$.ajax({
				url: 'https://api.svenglish.cn/api/payment/pretend',
				type: 'POST',
				contentType: 'application/json',
				data: JSON.stringify({
					objectType: "COURSE",
					objectId: orderId
				}),
				success:function(data){
					//成功
					if (data.code==1) {
						location.href = 'group.html?groupOrderId=' + groupOrderId;
					}else{
						//关闭loading
						guigu.hideLoading();
						guigu.showModal({
							content: data.msg,
							showCancel: false
						});
					}
				},
				fail(res) {
					//关闭loading
					guigu.hideLoading();
					guigu.showModal({
						content: '请求失败，请重试！',
						showCancel: false
					});
				}
			});
			
		},
		isWeiXin(){
			var ua = window.navigator.userAgent.toLowerCase();
			if(ua.match(/MicroMessenger/i) == 'micromessenger'){
				return true;
			}else{
				return false;
			}
		},
		submitFn(){
			this.createGroup();
		},
		locationFocus(){
			this.showSearch = true;
		},
  },
  watch:{
    
  },
	mounted() {
		var self = this;

		var wxUserInfo = localStorage.getItem('wxUserInfo');
		if(wxUserInfo){
			var wxUserInfo = JSON.parse(wxUserInfo);
			this.openId = wxUserInfo.unionId;
		}


		var contactInfo = localStorage.getItem('contactInfo');
		if(contactInfo){
			var contactInfo = JSON.parse(contactInfo);
			this.contactName = contactInfo.contactName;
			this.contactPhone = contactInfo.contactPhone;
			this.courseId = this.getCourseId(contactInfo.courseName);

			// 判断是否有推荐码
			if (/Referral/.test(contactInfo.source)) {
				this.referral = contactInfo.source.split('Referral: ')[1];
			}
		}


		window.addEventListener('message', function(event) {
			// 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
			var loc = event.data;
			if (loc && loc.module === 'locationPicker') {//防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
				console.log(loc);
				self.changeLocation = loc;
				self.contactLocation = loc.poiname === '我的位置' ? loc.poiaddress : loc.poiname;

				setTimeout(function(){
					self.showSearch = false;
				},300);
			}
		}, false);


	}
});



